import axios from "axios";
import util from './util';
import parseAPNG, { APNG } from "apng-js";
import { FrameType, singleFrame, OriginDtsType } from "./type";
import Player from "./player";

/**
 * 动图播放器
 */
export default class ApngPlay {


    static canvas = document.createElement("canvas");

    static apngs = new Map();

    imgUrl: string;
    ctx: CanvasRenderingContext2D | null;
    playObj: Player;
    constructor() {
        // this.imgUrl = imgUrl;
    }

    get canvas() {
        return ApngPlay.canvas;
    }

    async loopList(imgList: OriginDtsType[]) {
        for (const iterator of imgList) {
            await this.init(iterator);
        }
        await this.playAll(imgList);
    }

    loadApng(eachFrame: FrameType, ref) {
        if (!ApngPlay.apngs.get(ref)) {
            ApngPlay.apngs.set(ref, eachFrame);
        }
    }


    async init(iterator: OriginDtsType) {
        const res = await axios.get(iterator.imgPic, { method: "post", responseType: "blob" });
        const blob = new Blob([res.data]);
        const reader = new FileReader();

        await new Promise<void>((resolve) => {
            reader.onload = () => resolve();
            reader.readAsArrayBuffer(blob);
        });
        const frames: singleFrame[] = [];
        const apng = (parseAPNG(reader.result as ArrayBuffer) as APNG);

        this.canvas.width = apng.width;
        this.canvas.height = apng.height;
        this.ctx = this.canvas.getContext('2d');
        await apng.createImages();
        const { playTime, numPlays } = apng;
        apng.frames.forEach(({ imageElement, left, top, delay }) => {
            this.ctx.drawImage(imageElement, left, top);
            const blob = util.canvasToBlob(this.canvas);
            frames.push({
                frame: blob,
                delay,
            })
        })
        this.loadApng({ frames, playTime, numPlays }, iterator.imgRef.current)

    }

    playAll(imgList: OriginDtsType[]) {
        imgList.map(({ imgRef }, i) => {
            // 将play对象传递给外部
            const o = new Player(ApngPlay.apngs.get(imgRef.current), false, imgRef.current);
            imgList[i].obj = o;
        })
    }

    play(imgRef: HTMLImageElement, startFrame?, endFrame?, startLoopPlay?, endLoopPlay?) {
        this.playObj = new Player(ApngPlay.apngs.get(this.imgUrl), true, imgRef, startFrame, endFrame, startLoopPlay, endLoopPlay);
    }

    pause() {
        this.playObj._paused = true;
    }



    // shouldComponentUpdate(nextProps: Readonly<Props>, nextState: Readonly<State>, nextContext: any): boolean {

    //     const { src } = nextProps;
    //     if (nextProps.src !== this.props.src) {
    //         this.loadApng(src);
    //     }



    // }

    // getFrame(index: number) {

    //     const { src } = this.props;

    //     const frames = ApngPlay.apngs.get(src);

    //     img.src = frames[i].blob;

    // }

}